package com.kalix.mplive.mooc.biz;

import com.kalix.framework.core.api.persistence.JsonData;
import com.kalix.framework.core.impl.biz.GenericBizServiceImpl;
import com.kalix.mplive.mooc.api.biz.IMoocApplicationBeanService;
import com.kalix.mplive.mooc.api.dao.IMoocApplicationBeanDao;
import com.kalix.mplive.mooc.api.dto.MoocApplicationDTO;
import com.kalix.mplive.mooc.api.dto.MoocChapterDTO;
import com.kalix.mplive.mooc.api.dto.MoocDetailsDTO;
import com.kalix.mplive.mooc.api.dto.MoocReasonDTO;
import com.kalix.mplive.mooc.entities.MoocApplicationBean;
import com.kalix.mplive.mooc.entities.MoocChapterBean;
import com.kalix.mplive.mooc.entities.MoocSectionBean;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName MoocApplicationBeanServiceImpl
 * @Author ZhaoHang
 * @Date 2019/10/24 10:42
 */
public class MoocApplicationBeanServiceImpl extends GenericBizServiceImpl<IMoocApplicationBeanDao, MoocApplicationBean> implements IMoocApplicationBeanService {

    /**
     * 课程申请提交
     * @param className
     * @param classIntroduce
     * @param teacher
     * @param teacherIntroduce
     * @param classCover
     * @param teacherId
     * @param departmentId
     * @param specialityId
     * @param classTypeId
     * @param openTime
     * @param isAppraise
     * @param charge
     * @param classOpen
     * @return     返回课程id为了前台继续添加章节
     */
    @Override
    public MoocApplicationBean getSubmit(String className, String classIntroduce, String teacher, String teacherIntroduce, String classCover, long teacherId, long departmentId, long specialityId, long classTypeId, String openTime, Boolean isAppraise, Boolean charge,int classOpen) {
        MoocApplicationBean moocApplicationBean = new MoocApplicationBean();
        moocApplicationBean.setAppraise(isAppraise);
        moocApplicationBean.setBrowseNum(0);
        moocApplicationBean.setCharge(charge);
        moocApplicationBean.setClassCover(classCover);
        moocApplicationBean.setClassIntroduce(classIntroduce);
        moocApplicationBean.setClassName(className);
        moocApplicationBean.setClassTypeId(classTypeId);
        moocApplicationBean.setDepartmentId(departmentId);
        moocApplicationBean.setTeacherIntroduce(teacherIntroduce);
        moocApplicationBean.setIsOpen(0);
        moocApplicationBean.setJudgeOpen("f");
        moocApplicationBean.setTeacher(teacher);
        moocApplicationBean.setTeacherId(teacherId);
        moocApplicationBean.setSpecialityId(specialityId);
        moocApplicationBean.setClassOpen(classOpen);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = null;
        try {
            d = sdf.parse(openTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        moocApplicationBean.setOpenTime(d);
        MoocApplicationBean back = dao.save(moocApplicationBean);
        return back;
    }


    /**
     *
     * @return  获取推荐课程
     */
    @Override
    public JsonData getRecommend() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//设置日期格式
        String time = df.format(new Date());
        String sql = "select * from mplive_moocApplication a where a.isRecommend = true and " +
                "a.classOpen = 1 and openTime <= to_date('"+time+"','yyyy-mm-dd hh24:mi:ss')";
        List<MoocApplicationBean> list = dao.findByNativeSql(sql, MoocApplicationBean.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long) list.size());
        return jsonData;
    }

    /**
     *
     * @return  获取开课的章节信息
     */
    @Override
    public MoocApplicationDTO getClassInChapter() {
//        String getClassIdSql = "select distinct m.classid from mplive_moocchapter m,(select chapterid from mplive_moocsection " +
//                "where issectionopen = 1) a where m.ischapteropen = 1 and a.chapterid = m.id";
        String getClassIdSql = "select * from mplive_moocapplication where classOpen = 1";
//        List<Long> listByClassId = dao.findByNativeSql(getClassIdSql,Long.class);
        List<MoocApplicationBean> list = dao.findByNativeSql(getClassIdSql,MoocApplicationBean.class);
//        for(int j= 0;j<listByClassId.size();j++){
//            String getClassSql = "select * from mplive_moocapplication where id = "+ listByClassId.get(j);
//            List<MoocApplicationBean> tempList = dao.findByNativeSql(getClassSql,MoocApplicationBean.class);
//            list.add(tempList.get(0));
//        }
        List<MoocApplicationDTO> mlist = new ArrayList<>();
        MoocApplicationDTO moocApplicationDto = new MoocApplicationDTO();
        moocApplicationDto.setId(-1);
        for (int i = 0; i < list.size(); i++) {
            MoocApplicationDTO mooc = new MoocApplicationDTO();
            mooc.setId(list.get(i).getId());
            mooc.setText(list.get(i).getClassName());
            List<MoocApplicationDTO> tempList = new ArrayList<>();
            mooc.setChildren(tempList);
            mlist.add(mooc);
        }
        moocApplicationDto.setChildren(mlist);
        return moocApplicationDto;
    }

    /**
     *
     * @return  获取通过审核的课程的章节信息
     */
    @Override
    public MoocApplicationDTO getExamineChapter() {
        String getClassIdSql = "SELECT mm.* FROM" +
                " mplive_moocapplication mm," +
                "(SELECT DISTINCT M .classid FROM mplive_moocchapter M," +
                "(SELECT chapterid FROM mplive_moocsection s WHERE s.issectionopen = 0 ) A," +
                "(SELECT ID FROM mplive_moocchapter WHERE ischapteropen = 0 ) B WHERE" +
                " A.chapterid = M . ID or B.ID = M . ID ) aa WHERE" +
                " mm. ID = aa.classid AND mm.isopen = 1";
        List<MoocApplicationBean> list = dao.findByNativeSql(getClassIdSql,MoocApplicationBean.class);
//        List<MoocApplicationBean> list = new ArrayList<>();
//        for(int j= 0;j<listByClassId.size();j++){
//            String getClassSql = "select * from mplive_moocapplication where id = "+ listByClassId.get(j);
//            List<MoocApplicationBean> tempList = dao.findByNativeSql(getClassSql,MoocApplicationBean.class);
//            list.add(tempList.get(0));
//        }
        List<MoocApplicationDTO> mlist = new ArrayList<>();
        MoocApplicationDTO moocApplicationDto = new MoocApplicationDTO();
        moocApplicationDto.setId(-1);
        for (int i = 0; i < list.size(); i++) {
            MoocApplicationDTO mooc = new MoocApplicationDTO();
            mooc.setId(list.get(i).getId());
            mooc.setText(list.get(i).getClassName());
            List<MoocApplicationDTO> tempList = new ArrayList<>();
            mooc.setChildren(tempList);
            mlist.add(mooc);
        }
        moocApplicationDto.setChildren(mlist);
        return moocApplicationDto;
    }

    /**
     * 学生端筛选课程
     * @param departmentId  系id
     * @param specialityId  专业id
     * @param classTypeId   课程类型id
     * @param date  年份
     * @param moocPage  页数
     * @return
     */
    @Override
    public JsonData getMoocClass(long departmentId, long specialityId, long classTypeId, String date, int moocPage) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//设置日期格式
        String time = df.format(new Date());
        String changeHot = "update mplive_moocapplication  set ishot = false";
        dao.updateNativeQuery(changeHot);
        JsonData jsonData = new JsonData();
        String sql = "SELECT * FROM mplive_moocapplication M WHERE" +
                " M.classOpen = 1 and openTime <= to_date('"+time+"','yyyy-mm-dd hh24:mi:ss')";
        if (departmentId != 0) {
            sql += " AND M .departmentid = " + departmentId;
        }
        if (specialityId != 0) {
            sql += " AND M .specialityid = " + specialityId;
        }
        if (classTypeId != 0) {
            sql += " AND M .classtypeid = " + classTypeId;
        }
        if (!date.equals("0")) {
            sql += " AND m.opentime between '" + date + "-01-1 00:00:00' and '" + date + "-12-31 23:59:59'";
        }
        sql+=" order by M.browseNum desc";
        List<MoocApplicationBean> list = dao.findByNativeSql(sql, MoocApplicationBean.class);
        if(list.size()>0){
            jsonData.setTotalCount((long) list.size());
            int numPage = 0;
            if (list.size() % 6 == 0) {
                numPage = list.size() / 6;
            } else {
                numPage = list.size() / 6 + 1;
            }
            List<List<MoocApplicationBean>> listPge = new ArrayList<>();
            for (int i = 0; i < numPage; i++) {
                List<MoocApplicationBean> temp = new ArrayList<>();
                for (int j = i * 6; j < (i + 1) * 6; j++) {
                    if (j==list.size()) {
                        break;
                    }
                    if(j<6){
                        list.get(j).setHot(true);
                    }else{
                        list.get(j).setHot(false);
                    }
                    temp.add(list.get(j));
                }
                listPge.add(temp);
            }
            jsonData.setData(listPge.get(moocPage - 1));
        }else{
            jsonData.setData(list);
        }
        return jsonData;
    }

    /**
     * 浏览量变更
     * @param id  课程id
     * @param browseNum   前台返回的浏览量
     */
    @Override
    public void plusBrowseNum(long id,int browseNum) {
        String sql = "update mplive_moocapplication  set browseNum = "+browseNum+" where id= "+id;
        dao.updateNativeQuery(sql);
    }

    /**
     * 获取课程详情
     * @param classId  课程id
     * @return
     */
    @Override
    public MoocDetailsDTO getClassDetails(long classId) {
        String sqlChapter = "select * from mplive_moocchapter where classId = "+classId;
        MoocDetailsDTO moocDetailsDTO = new MoocDetailsDTO();
        String classSql = "select * from mplive_moocapplication where id = "+classId;
        List<MoocApplicationBean> classList = dao.findByNativeSql(classSql,MoocApplicationBean.class);
        String teacherSql = "select s.name from sys_user s where s.id = '"+ classList.get(0).getTeacherId()+"'";
        List<String> teacherSqlList = dao.findByNativeSql(teacherSql,String.class);
        moocDetailsDTO.setClassName(classList.get(0).getClassName());
        moocDetailsDTO.setClassIntroduce(classList.get(0).getClassIntroduce());
        moocDetailsDTO.setTeacher(teacherSqlList.get(0));
        moocDetailsDTO.setTeacherIntroduce(classList.get(0).getTeacherIntroduce());
        moocDetailsDTO.setAppraise(classList.get(0).getAppraise());
        moocDetailsDTO.setBrowseNum(classList.get(0).getBrowseNum());
        moocDetailsDTO.setCharge(classList.get(0).getCharge());
        moocDetailsDTO.setRecommend(classList.get(0).getRecommend());
        moocDetailsDTO.setClassCover(classList.get(0).getClassCover());
        moocDetailsDTO.setIsOpen(classList.get(0).getIsOpen());
        moocDetailsDTO.setOpenTime(classList.get(0).getOpenTime());
        moocDetailsDTO.setClassTypeId(classList.get(0).getClassTypeId());
        moocDetailsDTO.setDepartmentId(classList.get(0).getDepartmentId());
        moocDetailsDTO.setSpecialityId(classList.get(0).getSpecialityId());
        String getClassType = "select name from mplive_classType where id = "+classList.get(0).getClassTypeId();
        List<String> listGetClassType = dao.findByNativeSql(getClassType,String.class);
        moocDetailsDTO.setClassType(listGetClassType.get(0));
        String getDepartment = "select name from mplive_school where id = "+classList.get(0).getDepartmentId();
        List<String> listGetDepartment = dao.findByNativeSql(getDepartment,String.class);
        moocDetailsDTO.setDepartment(listGetDepartment.get(0));
        String getSpeciality = "select name from mplive_school where id = "+classList.get(0).getSpecialityId();
        List<String> listGetSpeciality = dao.findByNativeSql(getSpeciality,String.class);
        moocDetailsDTO.setSpeciality(listGetSpeciality.get(0));
        String iconSql = "select s.icon from sys_user s where s.id = '"+ classList.get(0).getTeacherId()+"'";
        List<String> iconList = dao.findByNativeSql(iconSql,String.class);
        if(iconList.size()>0){
            moocDetailsDTO.setIcon(iconList.get(0));
        }
        List<MoocChapterBean> chapterList = dao.findByNativeSql(sqlChapter,MoocChapterBean.class);
        List<MoocChapterDTO> chapterDtoList = new ArrayList<>();
        for(int i=0;i<chapterList.size();i++){
            MoocChapterDTO moocChapterDTO = new MoocChapterDTO();
            moocChapterDTO.setChapterNum(chapterList.get(i).getChapterNum());
            moocChapterDTO.setChapterName(chapterList.get(i).getChapterName());
            moocChapterDTO.setIsChapterOpen(chapterList.get(i).getIsChapterOpen());
            String sqlSection = "select * from mplive_moocsection where chapterId = "+chapterList.get(i).getId();
            List<MoocSectionBean> sectionList = dao.findByNativeSql(sqlSection,MoocSectionBean.class);
            moocChapterDTO.setChildren(sectionList);
            chapterDtoList.add(moocChapterDTO);
        }
        moocDetailsDTO.setList(chapterDtoList);
        return moocDetailsDTO;
    }

    /**
     * 获取老师个人中心慕课中所有状态的课程
     * @param teacherId 老师id
     * @return
     */
    @Override
    public JsonData getTeacherClass(long teacherId) {
        String sqlGoing = "select * from mplive_moocapplication where teacherId = '"+teacherId+"' and classOpen = 0";
        String sqlOpen = "select * from mplive_moocapplication where teacherId = '"+teacherId+"' and classOpen = 1";
        String sqlFalse = "select * from mplive_moocapplication where teacherId = '"+teacherId+"' and classOpen = 2";
        List<List<MoocApplicationBean>> list = new ArrayList<>();
        List<MoocApplicationBean> goingList = dao.findByNativeSql(sqlGoing,MoocApplicationBean.class);
        List<MoocApplicationBean> openList = dao.findByNativeSql(sqlOpen,MoocApplicationBean.class);
        List<MoocApplicationBean> falseList = dao.findByNativeSql(sqlFalse,MoocApplicationBean.class);
        JsonData jsonData = new JsonData();
        list.add(goingList);
        list.add(openList);
        list.add(falseList);
        jsonData.setData(list);
        return jsonData;
    }

    /**
     * 根据关键字模糊搜索课程名或老师名相关课程
     * @param word  关键字
     * @param page  页数
     * @return
     */
    @Override
    public JsonData fuzzySearch(String word,int page) {
        String sql = "select * from (select * from mplive_moocapplication where isOpen = 1) a " +
                "where teacher like '%"+word+"%'  or className like '%"+word+"%'";
        List<MoocApplicationBean> list = dao.findByNativeSql(sql,MoocApplicationBean.class);
        JsonData jsonData = new JsonData();
        jsonData.setTotalCount((long)list.size());
        if(list.size()>0){
            int numPage = 0;
            if (list.size() % 3 == 0) {
                numPage = list.size() / 3;
            } else {
                numPage = list.size() / 3 + 1;
            }
            List<List<MoocApplicationBean>> listPge = new ArrayList<>();
            for (int i = 0; i < numPage; i++) {
                List<MoocApplicationBean> temp = new ArrayList<>();
                for (int j = i * 3; j < (i + 1) * 3; j++) {
                    if (j==list.size()) {
                        break;
                    }
                    if(j<3){
                        list.get(j).setHot(true);
                    }
                    temp.add(list.get(j));
                }
                listPge.add(temp);
            }
            jsonData.setData(listPge.get(page - 1));
        }else{
            jsonData.setData(list);
        }
        return jsonData;
    }

    /**
     * 获取没有通过审核课程的原因
     * @param classId
     * @return
     */
    @Override
    public JsonData getReason(long classId) {
        JsonData jsonData = new JsonData();
        String classReasonSql = "select * from mplive_moocapplication where  trim(reason)!='' and id = "+classId;
        List<MoocApplicationBean> classReason = dao.findByNativeSql(classReasonSql,MoocApplicationBean.class);
        List<MoocReasonDTO> moocReasonDTOList = new ArrayList<>();
        MoocReasonDTO moocReasonDTO = new MoocReasonDTO();
        if(classReason.size()>0){
            moocReasonDTO.setName(classReason.get(0).getClassName());
            moocReasonDTO.setReason(classReason.get(0).getReason());
            moocReasonDTOList.add(moocReasonDTO);
        }
        String chapterReasonSql ="select id,chapternum  as num,chaptername as name,reason from mplive_moocchapter where classId = "+classId+" order by chapternum";
//        String chapterReasonSql1 = "select id,chapternum  as num,chaptername as name,reason from mplive_moocchapter where classId = "+classId+" and ischapteropen = 2 UNION " +
//                "select  a.chapterid as id,a.sectionnum as num,a.sectionname as name,a.reason from mplive_moocsection a," +
//                "(select id,chapternum  as num,chaptername as name,reason from mplive_moocchapter where classId = "+classId+" and ischapteropen = 2 ) b where a.issectionopen = 2  and a.chapterid= b.id ORDER BY num ";
        List<MoocReasonDTO> moocChapterReasonDTOSList = dao.findByNativeSql(chapterReasonSql,MoocReasonDTO.class);
        String sectionReasonSql = "select  a.chapterid as id,a.sectionnum as num,a.sectionname as name,a.reason from mplive_moocsection a where a.issectionopen =2 order by sectionnum";
        List<MoocReasonDTO> moocSectionReasonDTOSList = dao.findByNativeSql(sectionReasonSql,MoocReasonDTO.class);
        if(moocChapterReasonDTOSList.size()>0){
            for(int i =0;i<moocChapterReasonDTOSList.size();i++){
                if(moocChapterReasonDTOSList.get(i).getReason()!=null){
                    MoocReasonDTO moocReasonDTOS = new MoocReasonDTO();
                    moocReasonDTOS.setReason(moocChapterReasonDTOSList.get(i).getReason());
                    moocReasonDTOS.setName(moocChapterReasonDTOSList.get(i).getName());
                    moocReasonDTOS.setNum(moocChapterReasonDTOSList.get(i).getNum());
                    moocReasonDTOList.add(moocReasonDTOS);
                }
                for(int j =0;j<moocSectionReasonDTOSList.size();j++){
                    MoocReasonDTO moocReasonDTOSs = new MoocReasonDTO();
                    if(moocSectionReasonDTOSList.get(j).getId()==moocSectionReasonDTOSList.get(i).getId()){
                        moocReasonDTOSs.setReason(moocSectionReasonDTOSList.get(j).getReason());
                        moocReasonDTOSs.setName(moocSectionReasonDTOSList.get(j).getName());
                        moocReasonDTOSs.setNum(moocSectionReasonDTOSList.get(j).getNum());
                        moocReasonDTOList.add(moocReasonDTOSs);
                    }
                }
            }
        }
        jsonData.setData(moocReasonDTOList);
        return jsonData;
    }

    @Override
    public JsonData getAllMoocClass() {
        String sql = "SELECT" +
                " M . ID,M .browsenum,M .charge,M .classcover,M .classintroduce,M .classname,M .classopen,C . NAME AS classtype,s. NAME AS department," +
                " M .isappraise,M .ishot,M .isopen,M .isrecommend,M .opentime,ss. NAME AS speciality,M .reason,M .teacherintroduce" +
                " FROM" +
                " mplive_moocapplication M,sys_user u,mplive_classtype C,mplive_school s,mplive_school ss" +
                " WHERE" +
                " M .teacherid = u. ID AND M .classtypeid = C . ID AND M .departmentid = s. ID AND M .specialityId = ss. ID";
        List<MoocApplicationBean> list = dao.findByNativeSql(sql,MoocApplicationBean.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        return jsonData;
    }
}
